/*!
 * Copyright (c) 2023-present StarDreamNet
 */
(document.loader || (document.loader = [])).push(["user", class {
    constructor() {
        this.id = location.pathname.split("user/")[1];
        this.me = null;
    };

    init_(require) {
        const { resize, dateSpanString } = require("index");
        const { loadPostsByData } = require("postlist");

        this.resize = resize;
        this.dateSpanString = dateSpanString;
        this.loadPostsByData = loadPostsByData.bind(require("postlist"));

        $.ajax("/api/user/get_status?t=" + Date.now(), {
            contentType: 'application/json',
        }).done((data) => {
            if (data.code == 200 && Number(this.id) == data.data.id) {
                this.me = data.data;
                this.initPersonal();
            } else {
                this.me = null;
            }
            this.initInfo();
            this.initUserPosts();
            this.pageSystem();
        });
    };

    initInfo() {
        $.ajax("/api/shequ/get_user/" + this.id + "?t=" + Date.now(), {
            contentType: 'application/json',
        }).done(function (data) {
            if (data.code == 200) {
                $(".app-user-main-info-text>*").first().attr("src", data.data.img)
                    .next().text(data.data.name);
            }
        }).fail(() => {
            dsnackbar('error', '加载失败')
        });
    }

    initPersonal() {
        $("#set-name").val(this.me.name);
        $("#set-img").val(this.me.img);
        $(".app-user-me-hide").removeClass("app-user-me-hide");
    }

    updateUserMessages() {
        if (!this.me) return;

        const $main = $('.app-user-messages');
        if ($main.css('display') == 'none') return; // 页面未显示，跳过
        if ($main.children().length > 0) return; // 消息已加载，跳过

        $.ajax("/api/get_message?t=" + Date.now(), {
            contentType: 'application/json',
        }).done((data) => {
            if (data.code != 200) {
                $main.html('<div style="padding: 20px;">加载失败</div>');
                return;
            }

            const messages = data.data;
            if (messages.length == 0) {
                $main.html('<div style="padding: 20px;">暂无消息</div>');
                return;
            }

            const reversedMessages = messages.reverse();

            reversedMessages.forEach((message) => {
                $main.append(this.addMessage(message));
                this.resize();
            });
        }).fail(() => {
            $main.html('<div style="padding: 20px;">加载失败</div>');
        });
    }

    addMessage(data) {
        const main = $('<div class="app-user-message">');

        const avatar = $('<img class="app-user-message-avatar">');
        const content = $('<div class="app-user-message-content">');

        const title = $('<div class="app-user-message-content-title">');
        const time = $('<div class="app-user-message-content-time">');
        const text = $('<div class="app-user-message-content-text" hidden>');

        time.text(this.dateSpanString(data.time * 1000, Date.now()));

        content.append(title, time, text);
        avatar.attr('src', data.user_img);
        main.append(avatar, content);

        const types = {
            'good'() {
                const user = $('<a>')
                    .attr('href', '/user/' + data.user_id)
                    .text(data.user_name);
                const post = $('<a>').attr('href', '/post/' + data.post_id)
                    .text(data.post_title);

                return {
                    title: [user, '点赞了你的帖子', post],
                    text: ``
                };
            },
            'talk'() {
                const user = $('<a>')
                    .attr('href', '/user/' + data.user_id)
                    .text(data.user_name);
                const post = $('<a>').attr('href', '/post/' + data.post_id)
                    .text(data.post_title);

                return {
                    title: [user, '回复了你的帖子', post],
                    text: data.talk_text
                };
            },
        }

        const typeFunc = types[data.type];

        if (!typeFunc) {
            main.html('<p>未知消息无法进行展示</p>');
        } else {
            const typeData = types[data.type]();

            typeData.title.forEach(v => {
                if (typeof v == 'string') {
                    v = $('<span>').text(v);
                }
                title.append(v);
            });

            if (!!typeData.text) {
                text.removeAttr('hidden').text(typeData.text);
            }
        }
        return main;
    }

    initUserPosts() {
        $.ajax('/api/shequ/get_posts?t=' + Date.now(), {
            method: 'POST',
            contentType: 'application/json',
            dataType: 'json',
            data: JSON.stringify({
                user_id: this.id,
            })
        }).done((data) => {
            if (data.code !== 200) {
                cards.append(`<p style="padding: 20px;">加载失败</p>`)
                return;
            }

            var d = data.data;
            var cards = $('.app-user-postlists');

            if (d.length > 0) {
                var goods = d.map(v => v.goods).reduce((a, b) => a + b);
                var posts = d.length;
                $("#usergoods").text(`获赞：${goods}`);
                $("#count-goods>h3").text(goods);
                $("#count-posts>h3").text(posts);

                d.forEach((item) => {
                    var postlist = $(`<div class="app-user-postlist"></div>`);
                    var info = $(`<div class="app-user-postlist-info"><h2></h2><span></span></div>`);
                    info.find("h2").text(item.title);
                    info.find("span").text(`浏览：${item.views} 点赞：${item.goods}`);

                    if (this.me !== null) {
                        var btns = $(`<div class="app-user-postlist-btns"></div>`);
                        var change = $(`<img class="app-user-postlist-btn" width="24" height="24">`);
                        change.attr("src", "/static/image/change.svg");
                        var del = $(`<img class="app-user-postlist-btn" width="24" height="24">`);
                        del.attr("src", "/static/image/del.svg");
                        btns.append(change, del);
                        postlist.append(btns);

                        change.on("click", () => {
                            window.open("/change_post/" + item.id);
                        });
                        del.on("click", () => {
                            swal({
                                icon: "warning",
                                title: "确认删除？",
                                text: "删除后不可恢复，请谨慎选择",
                                buttons: {
                                    cancel: "取消",
                                    confirm: "确认"
                                }
                            }).then(v => {
                                if (!v) return;
                                this.delPost(item.id).then(v => {
                                    if (!v) return;
                                    postlist.remove();
                                    dsnackbar('success', "删除成功");
                                });
                            });
                        });
                    }

                    postlist.append(info);
                    cards.append(postlist);

                    postlist.on("click", function ({ target }) {
                        if ($(target).hasClass("app-user-postlist-btn")) return;
                        window.open("/post/" + item.id);
                    });
                });
            } else {
                cards.append(`<p style="padding: 20px;">暂无帖子</p>`)
            }

            this.resize();

        }).fail(() => {
            cards.append(`<p style="padding: 20px;">加载失败</p>`)
        });
    };

    onPageChange() {
        this.updateUserMessages();
    }

    pageSystem() {
        var tabs = $(".app-user-main-tab");
        var pages = $(".app-user-main-page>div");
        var tabblock = $(".app-user-main-tabblock");
        var th = this;

        tabs.each((i, v) => {
            v = $(v)
            v.on("click", function () {
                tabs.each((_, v) => $(v).removeClass("active"));
                pages.each((_, v) => $(v).css("display", "none"));

                var pos = v.position();
                tabblock.css("left", `${pos.left}px`)

                v.addClass("active");
                $(pages[i]).css('display', '');
                th.resize();
                th.onPageChange();
            })
        })

        $('#send_set').on("click", function () {
            var da = {
                img: $('#set-img').val()
            };

            this.disabled = true
            $("#set-name,#set-img").prop("disabled", true);

            $.ajax('/api/set_info', {
                method: 'POST',
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify(da),
            }).done((data) => {
                this.disabled = false
                $("#set-name,#set-img").prop("disabled", false);

                if (data.code == 200) {
                    dsnackbar('success', "设置成功");
                } else {
                    dsnackbar('error', data.msg || "设置失败");
                }

            }).fail(() => {
                dsnackbar('error', "设置失败");
            });
        });

        $('#logout').on("click", function () {
            this.disabled = true

            $.ajax('/api/logout', {
                contentType: 'application/json',
            }).done((data) => {
                if (data.code == 200) {
                    swal.skip({
                        title: "退出登录成功",
                        to: "首页",
                        src: "/"
                    });
                } else {
                    this.disabled = false
                    dsnackbar('error', data.msg || "退出登录失败");
                }
            }).fail(() => {
                dsnackbar('error', "退出登录失败");
            });
        });

        $('#protect').on("click", function () {
            this.disabled = true

            $.ajax('/api/user/protect_user', {
                contentType: 'application/json',
            }).done((data) => {
                if (data.code == 200) {
                    swal.skip({
                        title: "保护成功",
                        to: "首页",
                        src: "/"
                    });
                } else {
                    this.disabled = false
                    dsnackbar('error', data.msg || "执行失败");
                }
            }).fail(() => {
                dsnackbar('error', "执行失败");
            });
        });
    };

    delPost(postId) { // 删帖
        return new Promise(resolve => {
            $.ajax(`/api/shequ/del_post/`, {
                method: 'POST',
                contentType: 'application/json',
                dataType: 'json',
                data: JSON.stringify({
                    post_id: postId
                })
            }).done(function (response) {
                if (response.code == 200) {
                    resolve(true)
                } else {
                    dsnackbar('error', response.msg);
                    resolve(false)
                }
            }).fail(function () {
                dsnackbar('error', "请稍后重试");
                resolve(false)
            })
        })
    };
}])